<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Expressions in Ruby</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Ruby, learn Ruby, operators, expressions, 
assignment, programming, language, scripts">
<meta name="description" content="In this part of the Ruby tutorial, we cover expressions.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container2">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>



<div class="content2">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>



<h1>Expressions in Ruby</h1>

<p>
In this part of the Ruby tutorial, we will talk about expressions. 
</p>

<p>
Expressions are constructed from operands and operators. The operators of 
an expression indicate which operations to apply to the operands. 
The order of evaluation of operators in an expression is determined by the 
<b>precedence</b> and <b>associativity</b> 
of the operators
</p>

<p>
An <b>operator</b> is a special symbol which indicates 
a certain process is carried out. Operators in programming languages are 
taken from mathematics. Programmers work with data. The operators are used 
to process data. An <b>operand</b> is one of the inputs 
(arguments) of an operator.
</p>

<div class="big_hor">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* big_horizontal */
google_ad_slot = "2904953388";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<p>
The following table shows common Ruby operators ordered by
precedence (highest precedence first):
</p> 


<table> 
  <tr> 
    <th>Category</th> 
    <th>Symbol</th>
  </tr> 
  <tr> 
    <td>Resolution, access operators</td>
    <td><code>:: .</code></td>     
  </tr> 
  <tr class="gray"> 
    <td>Array operators</td>
    <td><code>[ ] [ ]=</code></td>     
  </tr> 
  <tr> 
    <td>Exponentiation</td> 
    <td><code>**</code></td> 
  </tr> 
  <tr class="gray">
    <td>Not, complement, unary plus, minus</td> 
    <td><code>! ~ + -</code></td> 
  </tr> 
  <tr>
    <td>Multiply, divide, modulo</td>
    <td><code>* / %</code></td> 
  </tr> 
  <tr class="gray">
    <td>Addition, substraction</td> 
    <td><code>+ -</code></td> 
  </tr> 
  <tr>
    <td>Shift operators</td>
    <td><code>&lt;&lt; &gt;&gt;</code></td> 
  </tr> 
  <tr class="gray">
    <td>Bitwise and</td> 
    <td><code>&amp;</code></td> 
  </tr> 
  <tr>
    <td>Bitwise or, logical or</td>
    <td><code>^ |</code></td> 
  </tr> 
  <tr class="gray">
    <td>Relational operators</td> 
    <td><code>&gt;  &gt;=  &lt;  &lt;=</code></td> 
  </tr> 
  <tr>
    <td>Bitwise or, logical or</td>
    <td><code>^ |</code></td> 
  </tr> 
  <tr class="gray">
    <td>Equality, pattern match operators</td> 
    <td><code>&lt;=&gt; == === != =~ !~</code></td> 
  </tr> 
  <tr>
    <td>Logical and</td>
    <td><code>&amp;&amp;</code></td> 
  </tr> 
  <tr class="gray">
    <td>Logical or</td> 
    <td><code>||</code></td> 
  </tr> 
  <tr>
    <td>Range operators</td>
    <td><code>.. ...</code></td> 
  </tr> 
  <tr class="gray">
    <td>Ternary</td>
    <td><code>?:</code></td> 
  </tr> 
  <tr> 
    <td>Assignment operators</td> 
    <td><code>=   +=   -=   *=  **= /=   %=   &amp;=   |=   
    ^=   &lt;&lt;=   &gt;&gt;= ||= &amp;&amp;=</code></td> 
  </tr> 
  <tr class="gray">
    <td>Alternate negation</td>
    <td><code>not</code></td> 
  </tr> 
  <tr>
    <td>Alternate logical or, and </td>
    <td><code>or and</code></td> 
  </tr>  
</table> 

<p>
Operators on the same row of the table have the same precedence.
</p> 

<p>
An operator usually has one or two operands. Those operators that work 
with only one operand are called <b>unary operators</b>. 
Those who work with two operands are called <b>binary operators</b>. 
There is also one ternary operator (?:), which works with three operands.
</p>

<p>
Certain operators may be used in different contexts. For example the + operator.
From the above table we can see, that it is used in different cases. 
It adds numbers, concatenates strings, indicates the sign
of a number. We say, that the operator is <b>overloaded</b>. 
</p>

<h2>Sign operators</h2>

<p>
There are two sign operators. + and -. They are used to indicate or
change the sign of a value. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts +2
puts -2
</pre>

<p>
+ and - signs indicate the sign of a value. The plus sign can be used 
to indicate that we have a positive number. It can be omitted and it
is mostly done so.
</p>

<hr class="btm">

<pre class="code">
#!/usr/bin/ruby

a = 1

puts a
puts -(a)
puts -(-(a))
</pre>

<p>
The minus sign changes the sign of a value.  
</p>

<pre>
$ ./sign.rb
1
-1
1
</pre>

<p>
Output. 
</p>


<h2>The assignment operator</h2>


<p>
The assignment operator <b>=</b> assigns a value to a variable. A <b>variable</b> 
is a placeholder for a value. In mathematics, the <b>=</b> operator has a different
meaning. In an equation, the <b>=</b> operator is an equality operator. The left 
side of the equation is equal to the right one. 
</p>

<pre class="code">
x = 1
puts x # prints 1
</pre>

<p>
Here we assign a number to the x variable. 
</p>

<pre class="code">
x = x + 1
puts x # prints 2
</pre>

<p>
The previous expression does not make sense in mathematics. But it is legal in programming. 
The expression adds 1 to the x variable. The right side is equal to 2 and 2 is assigned to x. 
</p>

<pre class="code">
3 = x;
</pre>

<p>
This code example results in syntax error. We cannot assign a value to a literal. 
</p>

<h2>Resolution, member access operators</h2>

<p>
These two operators have the highest precedence level in the hierarchy
of the operators. Which means, that they are always evaluated first. 
</p>

<pre class="code">
#!/usr/bin/ruby

class MyMath
    Pi = 3.1415926535    
end

module People
    Name = "People"
end 

puts MyMath::Pi
puts People::Name
</pre>

<p>
In the first example, we present the :: namespace resolution operator. 
It allows to access a constant, module, or class defined 
inside another class or module. It is used to provide namespaces so that 
method and class names don't conflict with other classes by different authors.
</p>

<pre class="explanation">
class MyMath
    Pi = 3.1415926535    
end

module People
    Name = "People"
end 
</pre>

<p>
We have a simple module and a class. Each has one constant defined. 
</p>

<pre class="explanation">
puts MyMath::Pi
puts People::Name
</pre>

<p>
We use the :: operator to access constants from both.
</p>

<pre>
$ ./resolution.rb
3.1415926535
People
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
The dot . operator is a member access operator. It is used to
call methods of objects. 
</p>

<pre class="code">
#!/usr/bin/ruby


class Person
    
   def initialize name, age
       @name = name
       @age = age       
   end
   
   def info
       "#{@name} is #{@age} years old"
   end
    
end


p = Person.new "Jane", 17
puts p.info

puts "ZetCode".reverse
</pre>

<p>
In our example, we have two objets. One user defined and one
predefined. We use the dot operator to work with these objects. 
</p>

<pre class="explanation">
p = Person.new "Jane", 17
puts p.info
</pre>

<p>
In these two lines, the dot operator calls two methods, new and info. 
</p>

<pre class="explanation">
puts "ZetCode".reverse
</pre>

<p>
A string is a built-in object, which has a reverse method. This is being called.
</p>

<pre>
$ ./memberaccess.rb
Jane is 17 years old
edoCteZ
</pre>

<p>
Output.
</p>


<h2>Concatenating strings</h2>

<p>
In Ruby the + operator is also used to concatenate strings. When an operator is 
used in different contexts differently, we say that it is <b>overloaded</b>.
</p>


<pre class="code">
#!/usr/bin/ruby

puts "Return " + "of " + "the " + "King"
puts "Return ".+"of ".+ "the ".+"King"
</pre>

<p>
We join three strings together using string concatenation operator. 
</p>

<pre class="explanation">
puts "Return " + "of " + "the " + "King"
</pre>

<p>
We join four strings using + operator. 
</p>

<pre class="explanation">
puts "Return ".+"of ".+ "the ".+"King"
</pre>

<p>
Under the hood, the + operator is a Ruby method. The string literal is an 
object. We call a method of an object using the access (.) operator. 
</p>

<pre>
$ ./catstrings.rb 
Return of the King
Return of the King
</pre>

<p>
And this is, what we get. 
</p>


<h2>Increment, decrement operators</h2>

<p>
Ruby has no such operators. 
</p>

<pre>
x++;
x = x + 1;
...
y--;
y = y - 1;
</pre>

<p>
These are increment, decrement operators in C.
</p>

<p>
If you are familiar with Java, C, C++, you know these operators.
They are not available in Ruby. Python language does not have 
them too. 
</p>


<h2>Arithmetic operators</h2>

<p>
The following is a table of arithmetic operators in Ruby.
</p>

<table>
<tr>
<th>Symbol</th><th>Name</th>
</tr>
<tr><td>+</td><td>Addition</td></tr>
<tr class="gray"><td>-</td><td>Subtraction</td></tr>
<tr><td>*</td><td>Multiplication</td></tr>
<tr class="gray"><td>/</td><td>Division</td></tr>
<tr><td>%</td><td>Remainder</td></tr>
<tr class="gray"><td>**</td><td>Power</td></tr>
</table>


<p>
The following example shows arithmetic operations.
</p>

<pre class="code">
#!/usr/bin/ruby

a = 10
b = 11
c = 12

puts a + b + c
puts c - a
puts a * b
puts c / 3
puts c % a
puts c ** a
</pre>

<p>
In the preceding example, we use addition, subtraction, multiplication,
division and remainder operations. This is all familiar from the mathematics.
</p>

<pre class="explanation">
puts c % a
</pre>

<p>
The % operator is called the remainder or the modulo operator. It finds the 
remainder of division of one number by another. For example, 9 % 4, 9 modulo 4 is 1, 
because 4 goes into 9 twice with a remainder of 1.
</p>

<pre>
$ ./arithmetic.rb
33
2
110
4
2
61917364224
</pre>

<p>
Output of the example. 
</p>

<hr class="btm">

<p>
Next we will show the distinction between integer and floating 
point division.
</p>

<pre class="code">
#!/usr/bin/ruby

puts 5 / 2

puts 5 / 2.0
puts 5.0 / 2
puts 5.to_f / 2
</pre>

<p>
In the preceding example, we divide two numbers. 
</p>

<pre class="explanation">
puts 5 / 2
</pre>

<p>
Both operands are integers. We have done integer division. The returned value
of the division operation is an integer. When we divide two integers
the result is an integer.
</p>

<pre class="explanation">
puts 5 / 2.0
puts 5.0 / 2
puts 5.to_f / 2
</pre>

<p>
If one of the values is a a float (or both), we perform a
floating point division. A floating point
value has a decimal point. We can also call a <code>to_f</code>
method to convert an integer to a float. 
</p>

<pre>
$ ./division.rb
2
2.5
2.5
2.5
</pre>

<p>
Result of the division.rb program. 
</p>

<hr class="btm">

<p>
Ruby has other ways to perform divisions. These are available as method
calls. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts 5.div 2.0
puts 5.fdiv 2
puts 5.quo 2
puts 5.0.quo 2.0
</pre>

<p>
In the above example, we have a <code>div</code>, a <code>fdiv</code> and
a <code>quo</code> methods. 
</p>

<pre class="explanation">
puts 5.div 2.0
</pre>

<p>
The <code>div</code> method always performs integer division. Even if the operands
are floting point values. 
</p>

<pre class="explanation">
puts 5.fdiv 2
</pre>

<p>
The <code>fdiv</code> method always performs float division.
</p>

<pre class="explanation">
puts 5.quo 2
puts 5.0.quo 2.0
</pre>

<p>
The <code>quo</code> method performs the most accurate division.
It returns a float if either operand is float, otherwise rational.
</p>

<pre>
$ ./otherdivision.rb
2
2.5
5/2
2.5
</pre>



<h2>Boolean operators</h2>

<p>
In Ruby, we have the following logical operators. 
Boolean operators are also called logical. 
</p>

<table>
<tr>
<th>Symbol</th><th>Name</th>
</tr>
<tr><td>&amp;&amp;</td><td>logical and</td></tr>
<tr class="gray"><td>||</td><td>logical or</td></tr>
<tr><td>!</td><td>negation</td></tr>
</table>

<p>
Boolean operators deal with truth values. Ruby has additional alternative
boolean operators. These are <code>and</code>, <code>or</code> &amp; 
<code>not</code>. They do the same except
for the thing that they have a lower precedence level. This duplicity
is taken from the Perl language, where there was a need for boolean operators
with a lower precedence.
</p>

<pre class="code">
#!/usr/bin/ruby

x = 3
y = 8

puts x == y
puts y > x

if y > x then
    puts "y is greater than x"
end
</pre>

<p>
Many expressions result in a boolean value. Boolean values are used
in conditional statements. 
</p>

<pre class="explanation">
puts x == y
puts y > x
</pre>

<p>
Relational operators always result in a boolean value. These two lines
print false and true. 
</p>

<pre class="explanation">
if y > x then
    puts "y is greater than x"
end
</pre>

<p>
The body of the <code>if</code> statement is executed only if the condition 
inside the parentheses is met. The x > y returns true, so the message 
"y is greater than x" is printed to the terminal. 
</p>

<hr class="btm">

<pre class="code">
#!/usr/bin/ruby

puts true &amp;&amp; true
puts true &amp;&amp; false
puts false &amp;&amp; true
puts false &amp;&amp; false
</pre>

<p>
Example shows the logical and operator. 
It evaluates to true only if both operands are true.
</p>

<pre>
$ ./andoperator.rb
true
false
false
false
</pre>

<hr class="btm">

<p>
The logical or || operator evaluates to true, 
if either of the operands is true.
</p>

<pre class="code">
#!/usr/bin/ruby

puts true || true
puts true || false
puts false || true
puts false || false
</pre>

<p>
If one of the sides of the operator is true, the outcome of 
the operation is true. 
</p>

<pre>
$ ./oroperator.rb
true
true
true
false
</pre>

<hr class="btm">

<p>
The negation operator ! makes true false and false true. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts !0
puts !1
puts !true
puts !false

puts ! (4&lt;3)
puts ! "Ruby".include?("a")
</pre>

<p>
The example shows the negation operator in action.
</p>

<pre>
$ ./not.rb
false
false
false
true
true
true
</pre>

<hr class="btm">

<p>
The <code>||</code>, and <code>&amp;&amp;</code> operators 
are short circuit evaluated. <b>Short circuit evaluation</b> means 
that the second argument is only evaluated if the first argument does 
not suffice to determine the value of the expression: when the first 
argument of the logical and evaluates to false, the overall value must
be false; and when the first argument of logical or evaluates to true, 
the overall value must be true. (wikipedia)
Short circuit evaluation is used mainly to improve performance. 
</p>

<p>
An example may clarify this a bit more.  
</p>

<pre class="code">
#!/usr/bin/ruby


def one
    puts "Inside one"
    false
end

def two
    puts "Inside two"
    true
end

puts "Short circuit"

if one &amp;&amp; two
    puts "Pass"
end

puts "##############################"

if two || one
    puts "Pass"
end
</pre>

<p>
We have two methods in the example. They are used as operands
in boolean expressions. We will see, if they are called or not.
</p>

<pre class="explanation">
if one &amp;&amp; two
    puts "Pass"
end
</pre>

<p>
The one method returns false. The short circuit &amp;&amp;
does not evaluate the second method. It is not necessary.
Once an operand is false, the result of the logical conclusion is always
false. Only "Inside one" is only printed to the console. 
</p>

<pre class="explanation">
puts "##############################"

if two || one
    puts "Pass"
end
</pre>

<p>
In the second case, we use the || operator and use the two
method as the first operand.
In this case, "Inside two" and "Pass" strings are printed to
the terminal. It is again not necessary to evaluate the second
operand, since once the first operand evaluates to true, the 
logical or is always true.
</p>


<pre>
$ ./shortcircuit.rb
Short circuit
Inside one
##############################
Inside two
Pass
</pre>

<p>
Result of the shortcircuit.rb program. 
</p>


<h2>Relational Operators</h2>

<p>
Relational operators are used to compare values. These operators always 
result in boolean value. Relational operators are also called comparison 
operators.
</p>

<table>
    <tr>
        <th>Symbol</th><th>Meaning</th>
    </tr>
    <tr>
        <td>&lt;</td><td>less than</td>
    </tr>
    <tr class="gray">
        <td>&lt;=</td><td>less than or equal to</td>
    </tr>
    <tr>
        <td>&gt;</td>
        <td>greater than</td>
    </tr>
    <tr class="gray">
        <td>&gt;=</td><td>greater than or equal to</td>
    </tr>
</table>

<pre class="code">
#!/usr/bin/ruby

p 3 &lt; 4
p 3 &gt; 5
p 3 &gt;= 3
</pre>

<p>
The <code>3 &lt; 4</code> expression returns true, since 3 is smaller than 4.
The <code>3 &gt; 5</code> expression returns false, because it is not true
that 3 is greater than 5.
</p>


<h2>Bitwise operators</h2>

<p>
Decimal numbers are natural to humans. Binary numbers are native to computers. 
Binary, octal, decimal or hexadecimal symbols are only notations of the same number. 
Bitwise operators work with bits of a binary number. 
</p>

<table>
<tr>
<th>Symbol</th><th>Meaning</th>
</tr>
<tr><td>~</td><td>bitwise negation</td></tr>
<tr class="gray"><td>^</td><td>bitwise exclusive or</td></tr>
<tr><td>&amp;</td><td>bitwise and</td></tr>
<tr class="gray"><td>|</td><td>bitwise or</td></tr>
<tr><td>&lt;&lt;</td><td>left shift</td></tr> 
<tr class="gray"><td>&gt;&gt;</td><td>right shift</td></tr> 
</table>

<p>
Bitwise operators are seldom 
used in higher level languages like Ruby. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts ~ 7   # prints -8 
puts ~ -8  # prints 7

puts 6 &amp; 3  # prints 2
puts 3 &amp; 6  # prints 2

puts 6 ^ 3  # prints 5
puts 3 ^ 6  # prints 5

puts 6 | 3  # prints 7
puts 3 | 6  # prints 7

puts 6 &lt;&lt; 1  # prints 12
puts 1 &lt;&lt; 6  # prints 64

puts 6 &gt;&gt; 1  # prints 3
puts 1 &gt;&gt; 6  # prints 0
</pre>

<p>
In the above code example, we show all 6 operators.
</p>

<pre class="explanation">
puts ~ 7   # prints -8 
puts ~ -8  # prints 7
</pre>

<p>
The <b>bitwise negation operator</b> changes each 1 to 0 and 0 to 1. 
The operator reverts all bits of a number 7. One of the bits also determines, 
whether the number is negative or not. If we negate all the bits one more 
time, we get number 7 again. 
</p>

<pre class="explanation">
puts 6 &amp; 3  # prints 2
puts 3 &amp; 6  # prints 2
</pre>

<p>
The <b>bitwise and operator</b> performs bit-by-bit comparison between two numbers. 
The result for a bit position is 1 only if both corresponding bits in the operands are 1. 
</p>

<pre class="explanation">
puts 6 ^ 3  # prints 5
puts 3 ^ 6  # prints 5
</pre>

<p>
The <b>bitwise exclusive or operator</b> performs bit-by-bit 
comparison between two numbers. The result for a bit position is 1 if 
one or the other (but not both) of the 
corresponding bits in the operands is 1. 
</p>

<pre class="explanation">
puts 6 | 3  # prints 7
puts 3 | 6  # prints 7
</pre>

<p>
The <b>bitwise or operator</b> performs bit-by-bit comparison between two nubmers. 
The result for a bit position is 1 if either of the corresponding bits 
in the operands is 1.
</p>

<pre class="explanation">
puts 6 &lt;&lt; 1  # prints 12
puts 1 &lt;&lt; 6  # prints 64

puts 6 &gt;&gt; 1  # prints 3
puts 1 &gt;&gt; 6  # prints 0
</pre>

<p>
The <b>bitwise shift operators</b> shift bits to the right or left.
These operators are also called arithmetic shift. <!--Shifting  bits of the numbers 
to the right equals dividing them by 2. Shifting bits to the left equals
multiplying them by 2. -->
</p>



<h2>Compound assignment operators</h2>

<p>
The compound assignment operators consist of two operators. 
They are shorthand operators. 
</p>

<pre class="code">
#!/usr/bin/ruby

a = 0

a = a + 1
a += 1
puts a


b = 0

b = b - 8
b -= 8
puts b
</pre>

<p>
The += and -= compound operators are one of these shorthand operators. 
They are less readable than the full expressions but 
experienced programmers often use them. 
</p>

<pre class="explanation">
a = a + 1
a += 1
</pre>

<p>
These two lines do the same, they add 1 to the a variable. 
</p>

<p>
Other compound operators are: 
</p>

<pre>
-=   *=  **=  /=   %=   &amp;=   |=   &lt;&lt;=   &gt;&gt;= 
</pre>



<h2>Operator precedence</h2>

<p>
The <b>operator precedence</b> tells us which operators are evaluated first. 
The precedence level is necessary to avoid
ambiguity in expressions. 
</p>

<p>
What is the outcome of the following expression? 28 or 40?
</p>

<pre>
 3 + 5 * 5
</pre>

<p>
Like in mathematics, the multiplication operator has a higher 
precedence than addition operator. So the outcome is 28.
</p>

<pre>
(3 + 5) * 5
</pre>

<p>
To change the order of evaluation, we can use parentheses.
Expressions inside parentheses are always evaluated first. 
</p>

<pre class="code">
#!/usr/bin/ruby

puts 3 + 5 * 5
puts (3 + 5) * 5

puts ! true | true
puts ! (true | true)
</pre>

<p>
In this code example, we show some common expressions. 
The outcome of each expression is dependent on the precedence level.
</p>

<pre class="explanation">
puts 3 + 5 * 5
</pre>

<p>
This line prints 28. The multiplication operator has a higher precedence
than addition. First the product of 5*5 is calculated. Then 3 is added. 
</p>


<pre class="explanation">
puts ! true | true
</pre>

<p>
In this case, the negation operator has a higher precedence. First, 
the first true value is negated to false, than the | operator 
combines false and true, which gives true in the end. 
</p>

<pre>
$ ./precedence.rb
28
40
true
false
</pre>


<h2>Associativity</h2>

<p>
Sometimes the precedence is not satisfactory to determine the outcome 
of an expression. There is another rule called
<b>associativity</b>. The associativity of operators determines 
the order of evaluation of operators with the <b>same</b>
precedence level. 
</p>

<pre>
9 / 3 * 3
</pre>

<p>
What is the outcome of this expression? 9 or 1? The multiplication, 
deletion and the modulo operator are left to right associated. 
So the expression is evaluated this way: <code>(9 / 3) * 3</code> 
and the result is 9.
</p>

<p>
Arithmetic, boolean, relational and bitwise operators are all left 
to right associated. 
</p>


<p>
On the other hand, the assignment operator is right associated. 
</p>

<pre class="code">
a = b = c = d = 0
print a, b, c, d # prints 0000 
</pre>

<p>
If the association was left to right, the previous 
expression would not be possible. 
</p>

<p>
The compound assignment operators are right to left associated. 
</p>

<pre class="code">
j = 0
j *= 3 + 1
puts j
</pre>

<p>
You might expect the result to be 1. But the actual result is 0.
Because of the associativity. The expression on the right is 
evaluated first and than the compound assignment operator is applied.
</p>

<h2>Range operators</h2>

<p>
Ruby has two range operators. They are used to quickly create a range
of objects. Most often a range of numbers or letters. 
</p>

<p>
The ".." range operator creates an inclusive range. The "..." creates 
an exclusive range, where the high value of the range is excluded. 
</p>

<pre class="code">
#!/usr/bin/ruby

p (1..3).to_a
p (1...3).to_a

p ('a' .. 'l').to_a
</pre>

<p>
In the example, we use both range operators to create a range of numbers
and characters. 
</p>

<pre class="explanation">
p (1..3).to_a
p (1...3).to_a
</pre>

<p>
These two lines create two ranges using both range operators. The range
objects are converted to arrays. The first range has values 1, 2 and 3 while
the second range has values 1 and 2.
</p>

<pre class="explanation">
p ('a' .. 'l').to_a
</pre>

<p>
Here we use the ".." range operator to create an array of letters from 'a' to 'l'. 
</p>

<pre>
$ ./range.rb
[1, 2, 3]
[1, 2]
["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]
</pre>

<p>
Example output.
</p>


<h2>The ternary operator</h2>

<p>
The ternary operator (?:) is a conditional operator. It is a convenient
operator for cases, where we want to pick up one of two values, depending
on the conditional expression.
</p>

<pre>
cond-exp ? exp1 : exp2
</pre>

<p>
If cond-exp is true, exp1 is evaluated and the result is returned. If
the cond-exp is false, exp2 is evaluated and its result is returned.
</p>

<pre class="code">
#!/usr/bin/ruby

age = 32

adult = age >= 18 ? true : false

if adult then
    puts "Adult"
else
    puts "Not adult"
end
</pre>

<p>
In most countries the adulthood is based on your age.
You are adult if you are older than a certain age.
This is a situation for a ternary operator.
</p>

<pre class="explanation">
adult = age >= 18 ? true : false
</pre>

<p>
First the expression on the right side of the assignment
operator is evaluated. The first phase of the ternary operator
is the condition expression evaluation. So if the age is greater
or equal to 18, the value following the ? character is returned.
If not, the value following the : character is returned.
The returned value is then assigned to the adult variable.
</p>

<pre>
$ ./ternary.rb
Adult
</pre>

<p>
A 32 years old person is adult.
</p>


<h2>Calculating prime numbers</h2>

<p>
We are going to calculate prime numbers.
</p>

<pre class="code">
#!/usr/bin/ruby

nums = (4..50).to_a

puts "Prime numbers:"

print "2 3 "

nums.each do |i|
    
    not_prime = false
    
    (2..Math.sqrt(i).ceil).each do |j|
        not_prime = true if i % j == 0    
    end
    
    print i, " " unless not_prime
    
end

puts 
</pre>

<p>
In the above example, we deal with several operators. A prime 
number (or a prime) is a natural number that has exactly two distinct 
natural number divisors: 1 and itself. We pick up a number and divide 
it by numbers, from 2 up to the picked up number. Actually, we don't have
to try all smaller numbers, we can divide by numbers up to the square
root of the chosen number. The formula will work. At the core of the algorithm
we use the remainder division operator, called also a modulo operator. 
</p>

<pre class="explanation">
nums = (4..50).to_a
</pre>

<p>
We will calculate primes from these numbers. 
</p>

<pre class="explanation">
print "2 3 "
</pre>

<p>
We skip the calculations for the 2, 3 numbers. They
are primes. 
</p>

<pre class="explanation">
not_prime = false
</pre>

<p>
The not_prime is a flag to indicate that the chosen number is not
a prime. We assume that the chosen number is a prime, untill it is proven
otherwise later. 
</p>

<pre class="explanation">
(2..Math.sqrt(i).ceil).each do |j|
    not_prime = true if i % j == 0    
end
</pre>

<p>
We are OK if we only modulo divide by numbers smaller than the square root of
a number in question. If the remainder division
operator returns 0 for any of the i values, then the number in
question is not a prime.
</p>

<pre class="explanation">
print i, " " unless not_prime
</pre>

<p>
We print the number if the not_prime flag is not set. 
</p>

<hr class="btm">

<p>
The above example was meant to demonstrate several operators.
There is in fact an easier way to calculate prime numbers.
Ruby has a module for calculating primes. 
</p>

<pre class="code">
#!/usr/bin/ruby

require 'prime'

Prime.each(50) do |i|
    print i, " "
end

puts
</pre>

<p>
An example calculating prime numbers up to 50 using the Ruby
prime module.  
</p>

<pre class="explanation">
require 'prime'
</pre>

<p>
We include the prime module. 
</p>

<pre class="explanation">
Prime.each(50) do |i|
    print i, " "
end
</pre>

<p>
We calculate primes up to the upper bound, 50.
</p>

<pre>
$ ./primes.rb
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 
</pre>

<p>
From this ouput we see primes between numbers 2 and 50. 
</p>


<p>
In this part of the Ruby tutorial, we covered the expressions. 
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 17, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

